package com.zhkj.crawl.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.regexp.internal.RE;
import com.zhkj.crawl.config.Config;
import com.zhkj.crawl.config.Constants;
import com.zhkj.crawl.config.FetchRankException;
import com.zhkj.crawl.entity.Listing;
import com.zhkj.crawl.entity.ResultAmz;
import com.zhkj.crawl.rank.AmzService;
import com.zhkj.crawl.rank.BaseService;
import com.zhkj.crawl.utils.AmzRankStrFinder;
import com.zhkj.crawl.utils.TimeDistance;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RetryService {

    @Autowired
    private ResultAmzService resultAmzService;

    public void doRetry(List<ResultAmz> results) {
        log.info("开始抓取retry listing {}条", results.size());
        int total = results.size();
        Config.rate.setTotal(total);
        List<List<ResultAmz>> partition = BusService.split(results);

        // 假设单条最大等待40s
        long timeout = partition.size() * (partition.get(0).size() * 40L);
        TimeDistance td = new TimeDistance();
        try {
            CompletableFuture.allOf(
                    partition.stream()
                            .map(s -> CompletableFuture.supplyAsync(() -> handlerList(s), BusService.exec))
                            .toArray(CompletableFuture[]::new)
            ).get(timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("执行错误", e);
        }
        td.dot();
        log.info("retry总条数{} 执行耗时{} 代理{} 结果{}", total, td.pop(), Config.proxySwitch, Config.rate);
    }


    private String handlerList(List<ResultAmz> value){
        log.info("开始处理{}条亚马逊数据", value.size());

        int size = value.size(), q = 0, succ = 0;
        try {
            for (ResultAmz resultAmz : value) {
                try {
                    ++q;
                    BaseService.ProductDetail detail = AmzService.start(resultAmz.getAsin(), resultAmz.getSite());

                    Element element = detail.getElement();
                    detail.setElement(null);
                    log.info("retry {} 的详情({}/{})：{}", detail.getItemId(), q, size, JSON.toJSONString(detail));
                    // 没取到rank
                    resultAmz.setTimes(resultAmz.getTimes() + 1);

                    if(StringUtils.isNotBlank(detail.getRank())){
                        resultAmz.setRankStr(detail.getRank());
                        AmzRankStrFinder.findAndFillNum(resultAmz);
                    }
                    succ++;
                }catch (Exception e){
                    log.error("amzHandlerErr", e);
                }
            }
        }finally {
            ChromeService.release();
        }

        try {
            Config.rate.addSuccess(succ);
            Config.rate.addHasRank((int) value.stream().filter(s -> StringUtils.isNotBlank(s.getRankStr())).count());
            int i = resultAmzService.updateRetryList(value);
            System.out.println("retry update:"+i);
        }catch (Exception e){
            List<String> batchRes = value.stream().map(s -> String.format("%s_%s", s.getSite(), s.getAsin())).collect(Collectors.toList());
            log.error(String.format("retryAmz结果出错 %s", batchRes), e);
        }

        return null;
    }

}
